package cn.touna.jss.modules.credit.consumer;

import cn.touna.risk.api.utils.JSONUtil;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.util.DateUtil;
import cn.touna.jss.common.util.DateUtils;
import cn.touna.jss.common.util.JssConstant;
import cn.touna.jss.modules.credit.entity.AuthFaceHistory;
import cn.touna.jss.modules.credit.service.AuthFaceHistoryService;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.utils.ServiceContext;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

/**
 * author: xl
 * time: 2018/8/9 10:04
 * description:人脸识别
 **/
@Component
public class AuthFaceHistoryConsumer {


    private static final Logger logger = LogManager.getLogger(AuthFaceHistoryConsumer.class);


    @Autowired
    AuthFaceHistoryService authFaceHistoryService;


    //@KafkaListener(topics = {"${kafka.topic.authfacehistory}"}, group = "risk-group-test0809")
    public void listern(ConsumerRecord<?, ?> record, Acknowledgment ack) {

        String traceId = record.key() == null ? ServiceContext.genUniqueId() : record.key().toString();
        TracerContextUtil.attachTraceId(traceId);
        logger.info("REQ【调用人脸识别记录消费】,traceId:{},topic:{},partition:{}", record.key(), record.topic(), record.partition());
        if (null != record.value()) {
            boolean isSuccess = true;
            try {
                JSONObject msgJson = JSONObject.parseObject(record.value().toString());
                if (msgJson == null) {
                    return;
                }
                saveRecord(traceId, msgJson);
            } catch (JSONException e) {
                logger.error("REQ【调用人脸识别记录消费JSON解析异常】,msg: {}", e);
            } catch (Exception e) {
                isSuccess = false;
                logger.error("REQ【调用人脸识别记录消费异常】,msg: {}", e);
            } finally {
                if (isSuccess) {
                    ack.acknowledge();
                }
            }
        }

    }


    private void saveRecord(String crNo, JSONObject msgJson) {
        JSONArray events = msgJson.getJSONArray("events");
        for (int i = 0; i < events.size(); i++) {
            JSONObject event = (JSONObject) events.get(i);
            String eventType = event.getString("event_type");
            if (JssConstant.AUTH_FACE_EVENT_TYPE.equals(eventType)) {
                AuthFaceHistory authFaceHistory = new AuthFaceHistory();
                JSONObject fields = event.getJSONObject("fields");
                String seqTns = event.getString("seq_tns");
                String mobile = fields.getString("mobile");
                String facRegoSimi = fields.getString("face_rego_simi");
                String isSucc = fields.getString("face_reco_is_succ");
                if(isSucc!=null){
                    boolean faceRecoIsSucc = isSucc.equals("true")?true:false;
                    authFaceHistory.setFaceRecoIsSucc(faceRecoIsSucc);
                }
                String userName = fields.getString("userid");
                String idCard = fields.getString("id_card");
                String resultid = fields.getString("resultid");
                authFaceHistory.setCrNo(crNo);
                authFaceHistory.setEventType(eventType);
                authFaceHistory.setIdNo(idCard);
                authFaceHistory.setMobile(mobile);
                authFaceHistory.setFaceRegoSimi(facRegoSimi);
                authFaceHistory.setName(userName);
                authFaceHistory.setResultCode(resultid);
                String exeTime= DateUtil.transferLongToDate(DateUtil.YYYY_MM_DD_HH_MM_SS,Long.valueOf(seqTns));
                authFaceHistory.setExeTime(exeTime);
                authFaceHistoryService.saveAuthFaceHistory(authFaceHistory);
            }

        }

        logger.info("REQ【调用人脸识别记录消费完成】,crNo:{}", crNo);
    }

}
